package com.example.demo.util;

import java.io.FileWriter;
import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.example.demo.HtmlToPdfUsingITextRenderer;
import com.example.demo.bo.PageVo;
import com.xuxueli.crawler.XxlCrawler;
import com.xuxueli.crawler.loader.strategy.HtmlUnitPageLoader;
import com.xuxueli.crawler.parser.PageParser;

public class FileUtil {
	public static void appendStringToFile(String contentToAppend, String fileName) {
        try (FileWriter fileWriter = new FileWriter(fileName, true)) { // 第二个参数为true表示追加模式
            fileWriter.write(contentToAppend);
        } catch (IOException e) {
            System.err.println("发生错误：无法追加内容到文件");
            e.printStackTrace();
        }
    }
	
	public static void saveStringToFile(String content, String fileName) {
        try (FileWriter writer = new FileWriter(fileName)) {
            writer.write(content);
            System.out.println("字符串已成功保存到文件: " + fileName);
        } catch (IOException e) {
            System.err.println("发生错误：无法保存内容到文件");
            e.printStackTrace();
        }
    }
	
	public static void getUrlHtmlToPdfUseXxlCrawler(String url, String fileName) {
		// 构造爬虫
        XxlCrawler crawler = new XxlCrawler.Builder()
                .setUrls(url)
                .setThreadCount(10)
                .setAllowSpread(false)
                .setUserAgent("ozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
                .setPageLoader(new HtmlUnitPageLoader())        // HtmlUnit 版本 PageLoader：支持 JS 渲染
                .setPageParser(new PageParser<PageVo>() {
                    @Override
                    public void parse(Document html, Element pageVoElement, PageVo pageVo) {
                    	String htmlContent = pageVoElement.html();
                    	
                    	htmlContent = htmlContent.replaceAll("<img\\b[^>]*>", "$0</img>");
                    	htmlContent = htmlContent.replaceAll("<source\\b[^>]*>", "$0</source>");
                    	HtmlToPdfUsingITextRenderer.convertHtmlToPdf("<html><body>"+htmlContent+"</body></html>", fileName);
                    }
                })
                .build();

        // 启动
        crawler.start(true);
    }
	
	public static void getUrlHtmlToPdf(String urlString, String fileName) {
		String htmlContent = HttpUtil.getHtml(urlString);
        
        Document doc = Jsoup.parse(htmlContent);
        Elements sections = doc.select("section");
        
        htmlContent = sections.html();
        
        Elements paragraph = sections.select(".pw-post-body-paragraph");
        for (Element element : paragraph) {
            Elements ems = element.select("em");
            if(!ems.isEmpty()) {
            	for (Element em : ems) {
            		Element emAdd = em.appendElement("em");
            		emAdd.text(HttpUtil.trans(em.text()));
				}
            } else {
            	element.append("<p class=\"pw-post-body-paragraph nv nw gs nx b hq ny nz oa ht ob oc od oe of og oh oi oj ok ol om on oo op oq gl bj\">"+HttpUtil.trans(element.text())+"</p>");
            }
		}
        htmlContent = sections.html();
        System.out.println(htmlContent);
        
        htmlContent = htmlContent.replaceAll("<img\\b[^>]*>", "$0</img>");
    	htmlContent = htmlContent.replaceAll("<source\\b[^>]*>", "$0</source>");
    	HtmlToPdfUsingITextRenderer.convertHtmlToPdf("<html><body>"+htmlContent+"</body></html>", fileName);
    }
}
